package com.ailanyin.modules.system.service.impl;


import cn.hutool.core.util.ObjectUtil;
import com.ailanyin.common.base.enums.UserEnum;
import com.ailanyin.common.base.exception.Assert;
import com.ailanyin.common.security.model.LoginUser;
import com.ailanyin.modules.system.domain.SysUser;
import com.ailanyin.modules.system.service.ISysRoleService;
import com.ailanyin.modules.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 用户验证处理
 *
 * @author ailanyin
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private ISysUserService userService;
    @Autowired
    private ISysRoleService sysRoleService;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser user = userService.getUserFromCache(username);
        checkUser(username, user);
        return createUserDetails(user);
    }


    private UserDetails createUserDetails(SysUser user) {
        Set<String> perms = new HashSet<>();
        List<Long> roleIds = new ArrayList<>();
        user.getRoles().forEach(sysRole -> {
            perms.addAll(sysRoleService.getRolePermsFromCache(sysRole.getRoleId()));
            roleIds.add(sysRole.getRoleId());
        });
        return new LoginUser(user.getUserId(), user.getNickName(), user.getDeptId(), user.getUserName(), user.getPassword(), perms, roleIds);
    }

    private void checkUser(String username, SysUser user) {
        if (ObjectUtil.isNull(user)) {
            Assert.fail("登录用户：" + username + " 不存在");
        } else if (UserEnum.DELETED.getCode().equals(user.getDelFlag())) {
            Assert.fail("对不起，您的账号：" + username + " 已被删除");
        } else if (UserEnum.DISABLE.getCode().equals(user.getStatus())) {
            Assert.fail("对不起，您的账号：" + username + " 已停用");
        }
    }
}
